#include "HufArc.h"

FILE * compres (FILE * fileToWrite,FILE * fileToRead,__HufTree * HufTree)
{
	unsigned char buf_in[8] = {0};
	unsigned char buf_out[8] = {0};
	unsigned char * hufTreeInStr = NULL;
	size_t un_bits = 0;
	size_t len = 0;
	int rc = 0;
	int i = 0;
	int rc2 = 0;
	int n = 1;
	__HufTree * head;
	unsigned char **tables = NULL;
	str_inf * inf = (str_inf *)calloc (1,sizeof(str_inf));
	tables = (unsigned char**) calloc (256,sizeof(char*));
	for (i = 0; i<256; i++)
		tables[i] = makeTables (i,0,HufTree,NULL);
	hufTreeInStr = HufTreeToStr (HufTree,&un_bits,&len);
	print (HufTree,NULL,0);
	fseek (fileToRead,0,SEEK_SET);
	if (un_bits == 0)
	{
		if ((rc = fwrite (hufTreeInStr,sizeof(char),len,fileToWrite)) != len)
			cl_exit (1,1);
	} else
	{
		if ((rc = fwrite (hufTreeInStr,sizeof(char),len-1,fileToWrite)) != (len-1))
			cl_exit (1,1);
		buf_out[0] = hufTreeInStr[len - 1];
	}
	if (un_bits == 8)
		un_bits = 0;
	else 
		inf->u_bits = un_bits;

	rc = 0;
	while (n == 1)
 	{
		if (rc == 0)
		{
			rc = fread (buf_in,sizeof(char),8,fileToRead);
			if (rc == 8)
			{
				inf->len = 8;
				inf->ind_char = 0;
				rc = _CharInBits (buf_out, buf_in,tables,inf);
				if (rc != 0)
				{
					rc = fwrite (buf_out,sizeof(char),8,fileToWrite);
					memset (buf_out,0,sizeof(char)*8);
					inf->pos = 0;
					if (rc != 8)
						cl_exit (3,5);
					rc = 0;
				}
			} else
			{
				if (rc == 0)
				{
					rc = fwrite (buf_out,sizeof(char),inf->pos,fileToWrite);
					if (rc != inf->pos)
						cl_exit (3,5);
					break;
				}
					inf->len = rc;
					rc = _CharInBits (buf_out, buf_in,tables,inf);
					rc2 = fwrite (buf_out,sizeof(char),inf->pos,fileToWrite);
					memset (buf_out,0,sizeof(char)*8);
					if (rc2 != inf->pos)
							cl_exit (3,5);
					if (rc == 2)
						while ((rc != 0) && (rc != 1))
						{
							rc = _CharInBits (buf_out, buf_in,tables,inf);
							rc2 = fwrite (buf_out,sizeof(char),inf->pos,fileToWrite);
							memset (buf_out,0,sizeof(char)*8);
								if (rc2 != inf->pos)
								cl_exit (3,5);
								inf->pos = 0;
						}
						break;
			}
		}
	}

				

			
	return NULL;


}